package com.mz.mattress.client.plan;

import com.mz.mattress.api.redis.RedisClient;
import com.mz.mattress.api.redis.RedisKeys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.*;

//任务派发器
@Slf4j
@Service
public class PlanSendService implements PlanTimer {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisClient redisClient;

    public static final ScheduledExecutorService EXECUTOR = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("planSendThread");
            t.setDaemon(true);
            return t;
        }
    });

    @PostConstruct
    public void init() {

        int delay = isTest ? 5 : 10;

        EXECUTOR.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                runTask();
            }
        }, delay, delay, TimeUnit.SECONDS);
    }

    @Override
    public void runTask() {

        try {

            List<Integer> list = redisClient.rangeAndRemoveByScore(RedisKeys.PLAN_TASK_SCORE_QUEUE, 0, System.currentTimeMillis());
            if (list == null) {
                log.info("plan_send_no_data");
                return;
            }

            log.info("plan_send_got_data_size=" + list.size());
            redisTemplate.boundListOps(RedisKeys.PLAN_TASK_QUEUE).rightPushAll(list.toArray());

        } catch (Throwable e) {
            log.info("plan_send_error", e);
        }
    }
}
